﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;

namespace UDPServer
{
    class Program
    {
        static void Main(string[] args)
        {
            //新建IP终结点实例对象，即127.0.0.1：2100;
            IPEndPoint iep = new IPEndPoint(IPAddress.Loopback, 2100);
            //新建一个UdpClient实例对象将其绑定到本地终结点，即UDP服务器在此终结点等待接收信息；
            UdpClient server = new UdpClient(iep);
            Console.WriteLine("UDP服务器在{0}等待接收纤细...", iep);
            //async关键字表示异步方法
            Task.Run(async () =>
            {
                while (true)
                {
                    var result = await server.ReceiveAsync(); //在此处异步等待，一旦有UDP客户端发过来信息，
                    //result就有结果，然后程序往下执行
                    string msg = Encoding.Default.GetString(result.Buffer);
                    Console.WriteLine("从{0}发来信息：{1}", result.RemoteEndPoint, msg);
                }
            });
            //此句不能省略，否则看不到结果
            Console.ReadKey();

        }
    }
}